package com.wteam.dragon.system.config;

import com.wteam.dragon.system.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置静态物理路径及配置FastJson
 * @Author 陈晓辉
 * @Date 2020/5/29 17:26
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Value("${spring.application.name}")
    private String name;

    /**
     * 静态路径设置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //获得系统的名字
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith(ConstantUtil.WIN)) {
            //addResourceHandler 请求路径
            //addResourceLocations 储存路径
            registry.addResourceHandler("/file/**")
                    .addResourceLocations("classpath:/file/");
        } else {
            registry.addResourceHandler("/"+ name +"/file/**")
                    .addResourceLocations("file:/"+ name +"/file/");
        }
    }

    /**
     * 解决跨域问题
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
                .allowedOriginPatterns("*")
                .maxAge(3600);
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

}